﻿using System.Web.Mvc;
using Microsoft.Web.Mvc;
using PCE.Core;
using PCE.Domain;
using PCE.Mvc.Filters;
using PCE.Mvc.Model;

namespace PCE.Mvc.Controllers
{
	public class RegisterController : Controller
	{
		private readonly ICustomerRegistrator _customerRegistrator;
		
		private readonly IAuthenticator _authenticator;

		public RegisterController(ICustomerRegistrator customerRegistrator, IAuthenticator authenticator)
		{
			_customerRegistrator = customerRegistrator;
			_authenticator = authenticator;
		}

		[HttpGet]
		public ActionResult Create()
		{
			return View();
		}

		[HttpPost]
		[PersistanceRequired]
		public ActionResult Create(RegistrationDetails details)
		{
			var customer = TryRegister(details);
			
			if (ModelState.IsValid && customer != null)
			{
				_authenticator.SignIn(customer.Id);
				return RedirectToAction("Edit", "Profile");
			}

			return View(details);
		}

		private Customer TryRegister(RegistrationDetails details)
		{
			if (details.Password != details.RepeatedPassword)
			{
				ModelState.AddModelError(string.Empty, "Пароли не совпадают");
				return null;
			}

			if (!_customerRegistrator.CheckExistance(details.Login, details.Email))
			{
				ModelState.AddModelError(string.Empty, "Пользователь с таким логином или адресом уже зарегистрирован");
				return null;
			}

			Customer result;
			
			if ((result = _customerRegistrator.Register(details.Login, details.Email, details.Password)) == null)
			{
				ModelState.AddModelError(string.Empty, "Не удалось зарегистрироваться");
				return null;
			}

			return result;
		}
	}
}